package com._dev.social.service.impl;

import com._dev.social.common.ErrorCode;
import com._dev.social.common.ResultUtils;
import com._dev.social.exception.BusinessException;
import com._dev.social.mapper.ThreadsMapper;
import com._dev.social.mapper.UsersMapper;
import com._dev.social.mode.domain.Threads;
import com._dev.social.mode.domain.Users;
import com._dev.social.service.FollowService;
import com._dev.social.service.ThreadsService;
import com._dev.social.service.UsersService;
import com._dev.social.mode.domain.response.ThreadResp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author Administrator
 * @description 针对表【threads】的数据库操作Service实现
 * @createDate 2024-11-06 17:54:06
 */
@Service
public class ThreadsServiceImpl extends ServiceImpl<ThreadsMapper, Threads>
        implements ThreadsService {
    @Autowired
    private ThreadsMapper threadMapper;
    @Resource
    private UsersMapper usersMapper;
    @Autowired
    private   UsersService usersService;
    @Autowired
    private FollowService followService;
    @Override
    public void addThread(Threads threads) {
        if (threads.getThread().isEmpty()||threads.getThread().isBlank()||usersService.isExistUser(threads.getUserId())) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 转换 uid 为 Integer 类型的 userId 并设置时间戳
        threads.setUserId(threads.getUserId());
        threads.setImage(threads.getImage());
        threads.setTimestamp(new java.util.Date()); // 使用当前时间
        this.save(threads);
    }

    @Override
    public List<Threads> getThreadById(String uid) {
        if(usersService.isExistUser(uid)){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Threads> threadsQueryWrapper = new QueryWrapper<>();
        threadsQueryWrapper.eq("userId", uid);
        List<Threads> threads = threadMapper.selectList(threadsQueryWrapper);
        Collections.reverse(threads);
        return threads;
    }

    @Override
    public List<Threads> getAllThreads() {
        return threadMapper.getAllThreads();
    }

    @Override
    public Boolean deleteThread(String userId, int tid) {

        if(usersService.isExistUser(userId)){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Threads> threadsQueryWrapper = new QueryWrapper<>();
        threadsQueryWrapper.eq("userId",userId)
                .eq("tid",tid);
        return threadMapper.delete(threadsQueryWrapper) >= 1;
    }

    @Override
    public Integer updateThread(Threads threads, String userId) {
        if(usersService.isExistUser(userId)){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 设置需要更新的字段
        threads.setUserId(userId);
        threads.setTimestamp(new java.util.Date());
        UpdateWrapper<Threads> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userId", userId)
                .eq("tid", threads.getTid());

        return threadMapper.update(threads, updateWrapper);
    }

    @Override
    public List<ThreadResp> getThreadsWithUserInfoOptimized() {
        // 查询所有话题
        QueryWrapper<Threads> queryWrapper = new QueryWrapper<>();
        List<Threads> threads = threadMapper.selectList(queryWrapper);
        List<ThreadResp> threadRespList = new ArrayList<>();

        // 查询所有用户信息并缓存到 Map 中，避免 N+1 查询问题
        Map<String, Users> userMap = new HashMap<>();
        List<Users> users = usersMapper.selectList(null);  // 查询所有用户
        for (Users user : users) {
            userMap.put(user.getUid(), user);  // 将用户按 uid 存入 Map
        }
        // 为每个话题填充用户信息
        for (Threads thread : threads) {
            // 获取用户信息
            Users user = userMap.get(thread.getUserId());  // 从缓存的 Map 中查找用户信息
            Users safetyUser = usersService.getSafetyUser(user);

            // 创建新的 ThreadResp 对象
            ThreadResp item = new ThreadResp();
            item.setThreads(thread);
            item.setUsers(safetyUser);  // 设置用户信息
            threadRespList.add(item);
        }
        // 倒序排列
        Collections.reverse(threadRespList);

        return threadRespList;
    }

    @Override
    public List<ThreadResp> getListFollowThreadById(String userId) {
        List<String> followList = new ArrayList<>(followService.getFollowList(userId));
        if (followList.isEmpty()) {
            return Collections.emptyList(); // 返回空列表而不是 null，避免 NPE
        }
        List<ThreadResp> threadResps = new ArrayList<>();

        for (String item : followList) {
            Users user = usersService.findUserById(item);
            Users safetyUser = usersService.getSafetyUser(user);

            QueryWrapper<Threads> threadsQueryWrapper = new QueryWrapper<>();
            threadsQueryWrapper.eq("userId", item);
            List<Threads> threads = threadMapper.selectList(threadsQueryWrapper);

            for (Threads thread : threads) {
                ThreadResp threadResp = new ThreadResp(); // 内循环中创建新实例
                threadResp.setUsers(safetyUser);
                threadResp.setThreads(thread);
                threadResps.add(threadResp); // 添加到列表
            }
        }
        return threadResps;
    }



}

